package com.menker.app.ui.generalweb;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.flyco.animation.BaseAnimatorSet;
import com.flyco.animation.FadeEnter.FadeEnter;
import com.flyco.animation.FadeExit.FadeExit;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.listener.OnOperItemClickL;
import com.flyco.dialog.widget.ActionSheetDialog;
import com.flyco.dialog.widget.NormalDialog;
import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.google.gson.Gson;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoImpl;
import com.jph.takephoto.compress.CompressConfig;
import com.jph.takephoto.model.CropOptions;
import com.jph.takephoto.model.InvokeParam;
import com.jph.takephoto.model.TContextWrap;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.permission.InvokeListener;
import com.jph.takephoto.permission.PermissionManager;
import com.jph.takephoto.permission.TakePhotoInvocationHandler;
import com.menker.app.Constants;
import com.menker.app.MyApp;
import com.menker.app.R;
import com.menker.app.biz.CurrentUser;
import com.menker.app.biz.ItemInfo;
import com.menker.app.biz.PageListInfo;
import com.menker.app.biz.WebPageInfo;
import com.menker.app.biz.WechatShareManager;
import com.menker.app.common.BaseWebViewToolbarActivity;
import com.menker.app.common.ToolbarOwner;
import com.menker.app.common.Utils;
import com.menker.app.dao.ItemDAO;
import com.menker.app.di.DaggerScope;
import com.menker.app.di.Injector;
import com.menker.app.rest.ApiHelper;
import com.menker.app.rest.result.ProductShareInfo;
import com.menker.app.rest.result.ShareInfo;
import com.menker.app.util.DialogUtils;
import com.menker.app.util.IntentUtils;
import com.menker.app.util.ShareUtils;
import com.menker.app.util.TaobaoUtils;
import com.menker.app.webview.WebViewManager;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.androidannotations.annotations.AfterInject;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.StringRes;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.parceler.Parcels;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import autodagger.AutoComponent;
import autodagger.AutoInjector;
import cn.sharesdk.framework.Platform;
import myandroid.library.util.ApplicationHelper;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @author J.Huang
 * @version 1.0
 */
@AutoComponent(
        dependencies = MyApp.class
)
@AutoInjector
@DaggerScope(GeneralWebViewActivity.class)
@EActivity(R.layout.activity_general_webview)
public class GeneralWebViewActivity extends BaseWebViewToolbarActivity<GeneralWebViewView, GeneralWebViewPresenter>
        implements GeneralWebViewView, TakePhoto.TakeResultListener, InvokeListener {

    @Inject
    ApiHelper mApiHelper;
    @Inject
    CurrentUser mCurrentUser;
    @Inject
    WechatShareManager mWechatShareManager;

    @StringRes(R.string.error_no_permission)
    String strErrNoPermission;
    @StringRes(R.string.error_no_internet)
    String strErrNoInternet;
    @StringRes(R.string.error_api)
    String strErrorApi;

    @ViewById(R.id.activity_general_webview_layout_main)
    LinearLayout mMainLayout;
    @ViewById(R.id.activity_general_webview_layout_splash)
    RelativeLayout mSplashLayout;
    @ViewById(R.id.iv_toolbar_menu_layout)
    LinearLayout mShareLayout;

    @ViewById(R.id.activity_general_webview_iv_collect)
    ImageView mCollectImage;
    @ViewById(R.id.activity_general_webview_test)
    BridgeWebView mTestWebView;

    boolean mReloaded = false;

    String lastValidUrl = "";

    private final int UPDATE_TOOBAR_TITLE_CODE = 666;
    private final int LOAD_MAIN_WEBVIEW_CODE = 777;
    private final int APP_PERMISSION = 100;


    private final int CAMERA_AND_PIC = 101;

    private TakePhoto mTakePhoto;
    private InvokeParam mInvokeParam;
    private ActionSheetDialog mDialog;
    private int mCurrentPosition = 0;

    private NormalDialog mNoPermissionDialog;

    private boolean intentByWelcome = false;
    private boolean phonePermissionTip = true;

    private boolean mByTaobaoUrl = false;
    private boolean mFirstRequest = true;

    private NormalDialog mPhonePermissionDialog;
    private ProductShareInfo mShareInfo;


    @AfterInject
    protected void initDI() {
        Intent intent = getIntent();
        if (intent != null && intent.getExtras() != null) {
            intentByWelcome = intent.getBooleanExtra("byWelcome",false);
        }
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
        sp.edit().putBoolean(Constants.API.KEY_SPLASH,false).commit();
    }

    @AfterViews
    protected void initData() {
        ApplicationHelper.getInstance().addActivity(this);

        getTakePhoto().onCreate(null);

        if (!intentByWelcome) {
            mSplashLayout.setVisibility(View.GONE);
            Injector.initGeneralWebViewActivityComponent().inject(this);
            initWeb();
        }else {
            checkPhoneState();
        }

    }

    private void initWeb() {
        final WebPageInfo webPageInfo = Parcels.unwrap(getIntent().getParcelableExtra(WebPageInfo.EXTRA_NAME));
//        final ProductShareInfo shareInfo = Parcels.unwrap(getIntent().getParcelableExtra(ProductShareInfo.EXTRA_NAME));

        final ProductShareInfo shareInfo = null;

        if (webPageInfo == null) {
            return;
        }

        mByTaobaoUrl = webPageInfo.byTaobaoUrl;

        setupUI(this);
        // 刷新功能等
        initCustomUI();

        mShareLayout.setVisibility(View.GONE);

        if (!webPageInfo.toolbarVisible && getSupportActionBar() != null) {
            getSupportActionBar().hide();
        } else {
            List<ToolbarOwner.MenuAction> menuActionList = new ArrayList<>();
//            if (!TextUtils.isEmpty(menuName)) {
//                ToolbarOwner.MenuAction menuAction = new ToolbarOwner.MenuAction(menuName, new Action0() {
//                    @Override
//                    public void call() {
//                    }
//                }, R.drawable.ic_add);
//
//                menuActionList.add(menuAction);
//            }

            ToolbarOwner.Config config = new ToolbarOwner.Config(webPageInfo.toolbarTitle, webPageInfo.toolbarUpButtonEnabled, menuActionList,
                    webPageInfo.toolbarTitleColor, webPageInfo.toolbarBgColor);
            mToolbarOwner.setConfig(config);
        }

        mWebViewManager.initJsBridge(mApiHelper, mCurrentUser);

        if (mByTaobaoUrl) {
            mTestWebView.setVisibility(View.VISIBLE);
        }

//        if (TextUtils.isEmpty(webPageInfo.url)) {
//            TaobaoUtils.showTaobaoPage(webPageInfo.pageId,webPageInfo.pageParams,this,this,mTestWebView);
//            Message msg = new Message();
//            msg.what = LOAD_MAIN_WEBVIEW_CODE;
//            msg.obj = webPageInfo.pageParams;
//            handler.sendMessageDelayed(msg,3000);
//        }else {
//            mWebViewManager.loadUrl(webPageInfo.url);
//        }
        mWebViewManager.loadUrl(webPageInfo.url);


        if (shareInfo != null) {
            mShareInfo = shareInfo;
            updateShareToolbar();
        }else {
            handler.sendEmptyMessageDelayed(UPDATE_TOOBAR_TITLE_CODE, 1000);
        }

    }


    private void checkPhoneState() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if(checkSelfPermission(Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED
                    ) {
                if (phonePermissionTip) {
                    // 申请一个（或多个）权限，并提供用于回调返回的获取码（用户定义)
                    requestPermissions(new String[]{
                            Manifest.permission.READ_PHONE_STATE,
                    }, APP_PERMISSION);
                }
            } else {
                checkNetwork();
            }
        } else {
            checkNetwork();
        }
    }

    void checkNetwork() {
        if (!Utils.Network.isNetworkAvailable()) {
            DialogUtils.showNoInternetDialog(this);
            return;
        }
        Injector.initGeneralWebViewActivityComponent().inject(this);
        initWeb();
        delayToNextAction();
    }

    @Background(delay = 2000)
    void delayToNextAction() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mSplashLayout.setVisibility(View.GONE);
            }
        });
    }

    @NonNull
    @Override
    public GeneralWebViewPresenter createPresenter() {
        return new GeneralWebViewPresenter(this);
    }

    @Override
    public void onResume() {
        mWebViewManager.onWebShow();
        handler.sendEmptyMessage(UPDATE_TOOBAR_TITLE_CODE);
        super.onResume();

//        if (mMainLayout != null) {
//            BridgeWebView webView = (BridgeWebView) findViewById(R.id.activity_general_webview_test);
//            webView.setVisibility(View.VISIBLE);
//            WebViewManager manager = new WebViewManager(this,this,webView);
//            manager.init();
//            manager.loadUrl(Constants.API.ORDER_URL);
//        }
    }

    @Override
    public void onDestroy() {
        handler.removeCallbacksAndMessages(null);

        if (mNoPermissionDialog != null) {
            mNoPermissionDialog.superDismiss();
            mNoPermissionDialog = null;
        }

        if (mPhonePermissionDialog != null) {
            mPhonePermissionDialog.superDismiss();
            mPhonePermissionDialog = null;
        }

        if (mDialog != null) {
            mDialog.superDismiss();
            mDialog = null;
        }

        mTestWebView.stopLoading();
        mTestWebView.clearHistory();
        mTestWebView.removeAllViews();
        // 释放资源
        mTestWebView.destroy();
        mTestWebView = null;

        ApplicationHelper.getInstance().removeActivity(this);

        super.onDestroy();
    }

    @Override
    public void onPause() {
        handler.removeCallbacksAndMessages(null);
        super.onPause();
    }

    /**
     * 重定义返回键操作
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            onBackPressed();
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onBackPressed() {
        if (!Utils.UI.isFastDoubleClick()) {
//            if (!mWebViewManager.goBack()) {
//            if (mByTaobaoUrl) {
//                IntentUtils.toNewGeneralWebViewActivity(this,new WebPageInfo("",Constants.API.ORDER_URL));
//            }

            ApplicationHelper.getInstance().removeActivity(this);
//            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        getTakePhoto().onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
        }

        switch (resultCode) {
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        getTakePhoto().onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    @UiThread
    protected void reloadWebView() {
        if (mWebViewManager != null) {
            mWebViewManager.reload();
            mReloaded = true;
        }
    }

    public void loadUrl(String url) {
        mWebViewManager.loadUrl(url);
    }

    @Background
    public void requestItemDetail(String itemUrl,String itemId) {

        if (!mFirstRequest) {
            return;
        }

        mFirstRequest = false;


        TaobaoUtils.showTaobaoPage("productDetail", itemId,this,this,mTestWebView);
        Message msg = new Message();
        msg.what = LOAD_MAIN_WEBVIEW_CODE;
        msg.obj = itemId;
        handler.sendMessageDelayed(msg,2000);

        String url = Constants.API.REQUEST_ITEM_URL.concat(itemUrl);
//        String url = "https://pub.alimama.com/items/search.json?startTkRate=8&q=https://detail.m.tmall.com/item.htm?id=558321478859";

        OkHttpClient client = new OkHttpClient.Builder().build();

        Request request = new Request.Builder()
                .get()
                .url(url)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String responseStr = response.body().string();
                try {
                    JSONObject jsonObject = new JSONObject(responseStr);
                    JSONObject data = jsonObject.getJSONObject("data");
                    PageListInfo pageListInfo = null;
                    String dataStr = data.getString("pageList");

                    if (!TextUtils.isEmpty(dataStr) && !dataStr.equals("null")) {
                        JSONObject pageList = data.getJSONArray("pageList").getJSONObject(0);
                        Gson gson = new Gson();
                        pageListInfo = gson.fromJson(pageList.toString(), PageListInfo.class);
                    }

                    if (pageListInfo == null) {
                        updateToolbar("");
                    }else {
                        presenter.getShare(pageListInfo);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                    updateToolbar("");
                }
            }
        });

    }

    public void enableItemSharing(String itemId) {
        if (!mByTaobaoUrl) {
            presenter.getShareInfo(itemId);
        }
    }

    public void disableItemSharing() {
        if (!mByTaobaoUrl) {
            mShareLayout.setVisibility(View.GONE);
        }

    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == UPDATE_TOOBAR_TITLE_CODE) {

                if (mShareInfo != null && mByTaobaoUrl) {

                    if (mWebViewManager.getTitle().equals("确认订单")) {
                        updateToolbarTitle(mWebViewManager.getTitle());
                    }else {
                        mShareLayout.setVisibility(View.VISIBLE);
                        if (mShareInfo.price > 0) {
                            mToolbarTitle.setText(getString(R.string.share_text_money, String.valueOf(mShareInfo.price)));
                        } else {
                            mToolbarTitle.setText(R.string.share_text_no_money);
                        }
                    }

                }else {
                    if (mWebViewManager != null && !TextUtils.isEmpty(mWebViewManager.getTitle())) {
                        if (!TaobaoUtils.isItemDetailsLink(mWebViewManager.getUrl())) {
                            updateToolbarTitle(mWebViewManager.getTitle());
                        }
                    }
                }

                handler.sendEmptyMessageDelayed(UPDATE_TOOBAR_TITLE_CODE, 1000);
            }else if (msg.what == LOAD_MAIN_WEBVIEW_CODE) {
                String pageParams = (String) msg.obj;
//                mWebViewManager.loadUrl("https://h5.m.taobao.com/awp/core/detail.htm?id=" + pageParams);
                mWebViewManager.reload();
            }
        }
    };

    public void setTitleByJS(String title) {
        handler.removeMessages(UPDATE_TOOBAR_TITLE_CODE);
        updateToolbarTitle(title);
    }

    void updateToolbarTitle(String title) {
        mToolbarTitle.setText(title);
        mShareLayout.setVisibility(View.GONE);
        if (title.equals("确认订单")) {
            mRefreshLayout.setEnableRefresh(false);
        }else {
            mRefreshLayout.setEnableRefresh(true);
            mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
                @Override
                public void onRefresh(RefreshLayout refreshlayout) {
                    refreshlayout.finishRefresh(1000);
                    mWebViewManager.reload();
                }
            });

            if (title.equals("专题")) {

                mCollectImage.setVisibility(View.VISIBLE);
                mCollectImage.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // TODO: 专题页添加喜欢的按钮
                    }
                });
            }
        }
    }

    public void updateShareToolbar() {
        if (mShareInfo == null) {
            return;
        }

        if (mShareInfo.price > 0) {
            mToolbarTitle.setText(getString(R.string.share_text_money, String.valueOf(mShareInfo.price)));
        } else {
            mToolbarTitle.setText(R.string.share_text_no_money);
        }

        ImageView imageView = (ImageView) findViewById(R.id.iv_toolbar_menu);
        imageView.setImageResource(R.drawable.ic_share);
        mShareLayout.setVisibility(View.VISIBLE);
        mShareLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ShareUtils.showSharePanel(GeneralWebViewActivity.this,mShareInfo);
                ClipboardManager clip = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                clip.setPrimaryClip(ClipData.newPlainText(null, mShareInfo.content));

                Utils.UI.showToastLong("内容已复制到剪贴板\n长按即可粘贴获取");
            }
        });

    }

    @UiThread
    @Override
    public void updateToolbar(final ShareInfo shareInfo) {
        updateToolbar(shareInfo.Price);

        mRefreshLayout.setEnableRefresh(true);
        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                refreshlayout.finishRefresh(1000);
                mWebViewManager.reload();
            }
        });

        if (shareInfo.ShowShare) {
            ImageView imageView = (ImageView) findViewById(R.id.iv_toolbar_menu);
            imageView.setImageResource(R.drawable.ic_share);
            LinearLayout layout = (LinearLayout) findViewById(R.id.iv_toolbar_menu_layout);
            layout.setVisibility(View.VISIBLE);
            layout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    ShareUtils.showSharePanel(GeneralWebViewActivity.this, mWechatShareManager, shareInfo.ShareText, shareInfo.ShareText, shareInfo.ShareUrl, shareInfo.ShareIcon);

                    ShareUtils.showSharePanel(GeneralWebViewActivity.this,mShareInfo);
                    ClipboardManager clip = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                    clip.setPrimaryClip(ClipData.newPlainText(null, shareInfo.ShareText));

                    Utils.UI.showToastLong("内容已复制到剪贴板\n长按即可粘贴获取");
                }
            });
        }
    }

    @UiThread
    public void updateToolbar(String price) {
        if (!TextUtils.isEmpty(price) && Float.valueOf(price) > 0) {
            mToolbarTitle.setText(getString(R.string.share_text_money, price));
            mShareLayout.setVisibility(View.VISIBLE);
        } else {
            mToolbarTitle.setText(R.string.share_text_no_money);
            mShareLayout.setVisibility(View.GONE);
        }
    }


    private boolean showPhonePermissionDialog() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if(checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                    || checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                    ) {

                BaseAnimatorSet bas_in = new FadeEnter();
                BaseAnimatorSet bas_out = new FadeExit();
                mPhonePermissionDialog = new NormalDialog(this);

                mPhonePermissionDialog.isTitleShow(false)
                        .btnNum(1)
                        .bgColor(Color.parseColor("#FFFFFF"))
                        .cornerRadius(5)
                        .content("应用需要\"电话状态\"权限才能正常使用\n请在\"设置\"中开启权限")
                        .contentGravity(Gravity.CENTER)
                        .contentTextSize(13)
                        .contentTextColor(Color.parseColor("#333333"))
                        .dividerColor(Color.parseColor("#CCCCCC"))
                        .btnText("确定")
                        .btnTextSize(15.5f)
                        .btnTextColor(Color.parseColor("#0092FF"))
                        .widthScale(0.7f)
                        .showAnim(bas_in)
                        .dismissAnim(bas_out)
                        .show();

                mPhonePermissionDialog.setOnBtnClickL(new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        mPhonePermissionDialog.dismiss();
                    }
                });

                return true;
            }
        }
        return false;
    }

    public void showTakePhotoDialog() {
        final String[] stringItems = {"拍照", "从系统相册选择"};
        mDialog = new ActionSheetDialog(GeneralWebViewActivity.this, stringItems, null);
        mDialog.isTitleShow(false).show();

        mDialog.setOnOperItemClickL(new OnOperItemClickL() {
            @Override
            public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
                mCurrentPosition = position;
                checkAllPermission();
            }
        });
    }

    private void checkAllPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                    || checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                    || checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
                    ) {

                requestPermissions(new String[]{
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.CAMERA,
                }, CAMERA_AND_PIC);
            } else {
                getPic();
            }
        } else {
            getPic();
        }
    }

    private void getPic() {

        File file = new File(Environment.getExternalStorageDirectory(), "/menke/avatar.jpg");
        if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
        Uri imageUri = Uri.fromFile(file);
        CropOptions cropOptions = new CropOptions.Builder().setAspectX(1).setAspectY(1).setWithOwnCrop(true).create();
        CompressConfig compressConfig = new CompressConfig.Builder().setMaxSize(50 * 1024).setMaxPixel(800).create();

        TakePhoto takePhoto = getTakePhoto();
        takePhoto.onEnableCompress(compressConfig, false);

        switch (mCurrentPosition) {
            case 0:
                takePhoto.onPickFromCaptureWithCrop(imageUri, cropOptions);
                break;
            case 1:
                takePhoto.onPickFromGalleryWithCrop(imageUri, cropOptions);
                break;
        }

        mDialog.dismiss();
    }

    public TakePhoto getTakePhoto() {
        if (mTakePhoto == null) {
            mTakePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this, this));
        }
        return mTakePhoto;
    }

    public void setProductShareInfo(ProductShareInfo shareInfo) {
        mShareInfo = shareInfo;
//        updateShareToolbar();
    }

    public ProductShareInfo getProductShareInfo() {
        return mShareInfo;
    }

    @Override
    public void takeSuccess(TResult result) {
        presenter.uploadImg(result.getImage().getOriginalPath());
    }

    @Override
    public void takeFail(TResult result, String msg) {

    }

    @Override
    public void takeCancel() {
    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());
        if (PermissionManager.TPermissionType.WAIT.equals(type)) {
            this.mInvokeParam = invokeParam;
        }
        return type;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.TPermissionType type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.handlePermissionsResult(this, type, mInvokeParam, this);

        switch (requestCode) {
            // requestCode即所声明的权限获取码，在checkSelfPermission时传入
            case APP_PERMISSION:
                boolean granted_1 = true;
                for (int i : grantResults) {
                    if (i != PackageManager.PERMISSION_GRANTED) {
                        granted_1 = false;
                        break;
                    }
                }

                if (granted_1) {
                    checkNetwork();
                } else {
                    showPhonePermissionDialog();
                }
                break;
            case CAMERA_AND_PIC:
                boolean granted = true;
                for (int i : grantResults) {
                    if (i != PackageManager.PERMISSION_GRANTED) {
                        granted = false;
                        break;
                    }
                }

                if (granted) {
                    // 获取到权限，作相应处理（调用定位SDK应当确保相关权限均被授权，否则可能引起定位失败）
                    getPic();
                } else {
                    // 没有获取到权限，做特殊处理
                    showDisablePermissionDialog();
                }
                break;
            default:
                break;
        }
    }

    private void showDisablePermissionDialog() {
        mNoPermissionDialog = new NormalDialog(this);

        mNoPermissionDialog.isTitleShow(false)
                .btnNum(1)
                .bgColor(Color.parseColor("#FFFFFF"))
                .cornerRadius(5)
                .content("无法上传头像图片\n请在\"设置\"中开启存储卡和相机权限")
                .contentGravity(Gravity.CENTER)
                .contentTextSize(13)
                .contentTextColor(Color.parseColor("#333333"))
                .dividerColor(Color.parseColor("#CCCCCC"))
                .btnText("确定")
                .btnTextSize(15.5f)
                .btnTextColor(Color.parseColor("#0092FF"))
                .widthScale(0.7f)
                .show();

        mNoPermissionDialog.setOnBtnClickL(new OnBtnClickL() {
            @Override
            public void onBtnClick() {
                mNoPermissionDialog.dismiss();
            }
        });
    }

    public interface OnUploadImgListener {
        void onFinish(String url);
    }

    public interface OnSharePicListener {
        void onShareFinished(boolean shareSuccess, Platform platform);
    }

    public void setOnUploadImgListener(OnUploadImgListener onUploadImgListener) {
        presenter.setOnUploadImgListener(onUploadImgListener);
    }

    public void setOnSharePicListener(OnSharePicListener onSharePicListener) {
        presenter.setOnSharePicListener(onSharePicListener);
    }

    public void sharePic(String imgUrl) {
        presenter.sharePic(imgUrl);
    }
}
